#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/time.h>
#include <stdint.h>

#include "mSC.h"
#include "display.h"


#define KEYQUEUELEN     (16)
uint16_t keyqueue[KEYQUEUELEN] = {0};
uint32_t lcdid = 0;

extern void SysTick_Handler(void);
void timerCallback(int sig);
void initlcd(void);
void setXYZ(int x,int y,int z);
void setConversely(uint8_t con); 
void setFrontRGB(uint32_t rgb); 
void setBackRGB(uint32_t rgb); 
void clear(void);           


void sysTickConfig(uint32_t f)
{
    struct itimerval tick;

    memset(&tick, 0, sizeof(tick));
    signal(SIGALRM,timerCallback);

    tick.it_value.tv_sec = 0;
    tick.it_value.tv_usec = 1000000/f;

    tick.it_interval.tv_sec = 0;
    tick.it_interval.tv_usec = 1000000/f;

    if(setitimer(ITIMER_REAL, &tick, NULL) < 0)
        msc_printf("Set timer failed!\n");
}

void timerCallback(int sig)
{
    SysTick_Handler();
}

void initTask(void *p)
{
    qCreate((void *)keyqueue,16,KEYQUEUELEN);
    displayRegister(&lcdid,initlcd,setXYZ,setConversely,setFrontRGB,setBackRGB,clear,putchar,NULL,NULL);
    displayClear();

    mscDeleteTask(initTask);
}

void ledBlink100msTask(void *p)
{
    static uint8_t i = 0;
    //displayByXYZ(3,5,0,"%s",(i ? "   ☼   \033[31m♥ \033[0m  ◯ ":"   ☀   \033[31m♡ \033[0m  ● ")); 
    display("\033[%d;%dH%s",3,5,(i ? "   ☼   \033[31m♥ \033[0m  ◯ ":"   ☀   \033[31m♡ \033[0m  ● ")); 
    fflush(stdout);
    qAddItem((void *)keyqueue,i);
    i = !i;
}

void ledBlink500msTask(void *p)
{
    static uint8_t i = 0;
    //displayByXYZ(3,7,0,"%s",(i ? "   ☼   \033[31m♥ \033[0m  ◯ ":"   ☀   \033[31m♡ \033[0m  ● ")); 
    display("\033[%d;%dH%s",3,7,(i ? "   ☼   \033[31m♥ \033[0m  ◯ ":"   ☀   \033[31m♡ \033[0m  ● ")); 
    fflush(stdout);
    i = !i;
}

void keyTask(void *p)
{
    uint32_t temp = 0;
    qOutItem((void *)keyqueue,(uint32_t *)&temp);
    //displayByXYZ(9,9,0,"%d",temp); 
    display("\033[%d;%dH\033[7m%d\033[0m",9,9,temp); 
    qCount((void *)keyqueue,(uint32_t *)&temp); 
    //displayByXYZ(3,9,0,"%d",temp); 
    display("\033[%d;%dH%d",3,9,temp); 
    //displayByXYZ(13,9,0,"%f",1234.5678); 
    display("\033[%d;%dH%f",13,9,1234.5678); 
}

int main(int argc,char *argv[])
{
    mscInit();
    
    mscCreateTask(MSC_TASK_ZERODELAY,0,0,NULL,initTask);
    mscCreateTask(MSC_TASK_MSDELAY,0,100,NULL,ledBlink100msTask);
    mscCreateTask(MSC_TASK_MSDELAY,0,500,NULL,ledBlink500msTask);
    mscCreateTask(MSC_TASK_MSDELAY,0,100,NULL,keyTask);

    mscStart();

    while(1)
    {
        pause();
    }
    return 0;
}


void initlcd(void)
{

}

void setXYZ(int x,int y,int z)
{
    printf("\033[%d;%dH",y + 1,x + 1);
}

void setConversely(uint8_t con) 
{
    (con ? printf("\033[7m") : printf("\033[0m"));
}

void setFrontRGB(uint32_t rgb) 
{
    printf("\033[%dm",rgb);
}

void setBackRGB(uint32_t rgb) 
{
    printf("\033[%dm",rgb);
}

void clear(void)
{
    printf("\033[2J");
}




